package com.taptech.doufu.ui.fragment

import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.taptech.doufu.R
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.SPKey
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.event.BaseEventBusBean
import com.taptech.doufu.ktexpand.format
import com.taptech.doufu.model.novel.bean.NovelDetailBean
import com.taptech.doufu.model.novel.bean.NovelRecommendBean
import com.taptech.doufu.presenter.novel.INovelReadEndView
import com.taptech.doufu.presenter.novel.NovelReadEndPresenter
import com.taptech.doufu.services.HomeMainServices
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.NovelDetailsActivity
import com.taptech.doufu.ui.activity.NovelReadEndActivity
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity
import com.taptech.doufu.ui.activity.weex.SimpleWeexTransparentActivity
import com.taptech.doufu.ui.adapter.NovelHotCommentAdapter
import com.taptech.doufu.ui.adapter.NovelRecommendAdapter
import com.taptech.doufu.ui.adapter.NovelRecommendGridAdapter
import com.taptech.doufu.ui.dialog.TipSingleBtnDialog
import com.taptech.doufu.ui.view.FlowerDialogManager
import com.taptech.doufu.ui.view.GiftDialogManager
import com.taptech.doufu.util.ScreenUtil2
import com.taptech.doufu.util.ShareUtils
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences
import kotlinx.android.synthetic.main.fragment_novel_read_end.*
import kotlinx.android.synthetic.main.view_article_comment_item.*
import kotlinx.android.synthetic.main.view_comment_item.*
import kotlinx.android.synthetic.main.view_novel_end_title_bar.*
import kotlinx.android.synthetic.main.view_novel_gift.*
import kotlinx.android.synthetic.main.view_novel_recommend_by_author.*
import kotlinx.android.synthetic.main.view_share_enter.*
import org.greenrobot.eventbus.EventBus


class NovelReadEndFragment:BaseMvpFragment<NovelReadEndPresenter>(), INovelReadEndView {

    private var hotCommentAdapter: NovelHotCommentAdapter? = null
    private var shareDialog: BottomSheetDialog? = null
    private var isYouthModel = false

    override fun getLayout(): Int {
        return R.layout.fragment_novel_read_end
    }

    override fun initPresenter() {
        var id = arguments?.getInt(Constant.ID) as Int
        mPresenter = NovelReadEndPresenter(activity!!,this, id)
        mPresenter.getNovelDetails()
    }

    override fun initView(rootView: View) {
        initMorePopupWindow()
        layRecommendAuthorReplace.setOnClickListener {
            mPresenter.getRecommendByAuthor()
        }

        layCollect.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            mPresenter.collectNovel()
        }

        layFlower.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(activity, "青少年模式不支持该功能", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            FlowerDialogManager.getInstance(activity,mPresenter.getProductionBean(),mPresenter.novelBean.shareUrl)
        }
        layReward.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(activity, "青少年模式不支持该功能", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            GiftDialogManager.getInstance(activity,mPresenter.getProductionBean())
        }
        layTicket.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(activity, "青少年模式不支持该功能", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            SimpleWeexTransparentActivity.startActivity(activity,"TFNovel/TFMonthTicket.js?present=1&id=${mPresenter.novelId}&count=${mPresenter.novelBean.month_ticket_sum}")
        }
        layArticleComment.setOnClickListener {
            var url = "vue/articalComment/TFArticalComment.js?novelId=${mPresenter.novelId}&isFromDetail=true"
            SimpleWeexActivity.startActivity(activity,url)
        }
        layComment.setOnClickListener {
            jumpToComment()
        }
        tvToAllComment.setOnClickListener {
            jumpToComment()
        }
        layBack.setOnClickListener {
            if (activity is NovelReadEndActivity) {
                //发送通知关闭阅读页面
                val eventBusBean = BaseEventBusBean()
                eventBusBean.tag = NovelSectionDetailsActivity.TAG_FINISH_ACTIVITY
                EventBus.getDefault().post(eventBusBean)
            }
            activity?.finish()
        }
        layMore.setOnClickListener {
            showMorePopupWindow()
        }
        layShare.setOnClickListener {
            shareMore()
        }
        layShareMore.setOnClickListener {
            shareMore()
        }
        layShareWeixin.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(activity, "青少年模式不支持该功能", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            val shareBean = mPresenter.getShareBean()
            shareBean.social_type = ShareType.Weixin
            ShareUtils.thirdPartyShare(activity,shareBean)
        }
        layShareWeibo.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(activity, "青少年模式不支持该功能", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            val shareBean = mPresenter.getShareBean()
            shareBean.social_type = ShareType.Weibo
            ShareUtils.thirdPartyShare(activity,shareBean)
        }
        layShareQQ.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(activity, "青少年模式不支持该功能", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            val shareBean = mPresenter.getShareBean()
            shareBean.social_type = ShareType.QQ
            ShareUtils.thirdPartyShare(activity,shareBean)
        }
        layShareTitle.setOnClickListener {
            if (isYouthModel) {
                return@setOnClickListener
            }
            var tip = "通过分享邀请好友，每成功邀请1位好友可得6张阅读券及随机礼包，多邀多得，上不封顶。\n" +
                    "\n" +
                    "邀请好友得福利，想要了解更多请查看“我的”-\"邀请好友”。"
            if (!mPresenter.novelBean.invitation_desc.isNullOrEmpty()){
                tip = mPresenter.novelBean.invitation_desc
            }
            val dialog = TipSingleBtnDialog(activity!!, R.style.updateDialog, tip)
            dialog.show()
        }
    }

    private fun setYouthModel() {
        val pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, activity, "")
        if (pwd != null && pwd.isNotEmpty()) {
            isYouthModel = true
            layArticleCommentMarginTop.visibility = View.GONE
            layArticleComment.visibility = View.GONE
            layCommentMarginTop.visibility = View.GONE
            layComment.visibility = View.GONE
            rvHotComment.visibility = View.GONE
            tvToAllComment.visibility = View.GONE
            layRecommendByAuthor.visibility = View.GONE
            layRecommendByNovel.visibility = View.GONE
        }
    }


    private fun shareMore() {

        if (isYouthModel) {
            Toast.makeText(activity, "青少年模式不支持该功能", Toast.LENGTH_LONG).show()
            return
        }
        if (shareDialog == null) {
            shareDialog = ShareUtils.getBottomDialog(activity,mPresenter.getShareBean())
        }
        shareDialog?.show()
    }


    private var mMorePopupWindow: PopupWindow? = null

    private fun initMorePopupWindow() {
        val inflater = LayoutInflater.from(activity)
        val mMoreView = inflater.inflate(R.layout.popup_reader_end_more, null)
        val lay = mMoreView.findViewById<View>(R.id.lay)
        lay.setOnClickListener {
            mMorePopupWindow?.dismiss()
        }

        val mReport = mMoreView.findViewById<LinearLayout>(R.id.popup_reader_more_report)
        mReport.setOnClickListener {

            val novelBean = mPresenter.novelBean
            HomeMainServices.reportContentRequest(activity,novelBean.user.userId,novelBean.object_type.toString(),novelBean.id.toString())
        }
        mReport.visibility = View.VISIBLE
        val mDetail = mMoreView.findViewById<LinearLayout>(R.id.popup_reader_more_detail)
        mDetail.visibility = View.VISIBLE
        mDetail.setOnClickListener {
            NovelDetailsActivity.startActivity(activity!!,mPresenter.novelId)
        }

        mMorePopupWindow = PopupWindow(mMoreView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        mMorePopupWindow?.animationStyle = R.style.Animation_Right_Left
        mMorePopupWindow?.setBackgroundDrawable(BitmapDrawable())
    }


    private fun showMorePopupWindow() {
        mMorePopupWindow?.showAtLocation(activity?.window?.decorView, Gravity.TOP or Gravity.RIGHT, ScreenUtil2.dip2px(10f), 0)
        mMorePopupWindow?.isFocusable = true
        mMorePopupWindow?.isOutsideTouchable = true
        mMorePopupWindow?.update()
    }


    private fun jumpToComment() {
        val url = "TFComment/TFAllComment.js"
        var map = HashMap<String,Any>()
        map["id"] = mPresenter.novelId
        SimpleWeexActivity.startActivity(activity,url,map)
    }


    override fun fillNovelDetail(bean: NovelDetailBean) {
        tvTitle.text = bean.title
        tvAuthorName.text = bean.user.name

        tvArticleCommentDesc.text =if (bean.star.isNullOrEmpty()) "" else "${bean.star}分/${bean.star_times}人参与"
        tvCommentDesc.text = if (bean.comment_times!=null) "${bean.comment_times}条" else ""
        tvTicketCount.text = "${bean.month_ticket_sum}"
        tvFlowerCount.text = bean.flowerCount.format()
        tvRewardCount.text = bean.reward_sum.format()
        if (bean.hot_comments != null && bean.hot_comments.size > 0) {
            hotCommentAdapter = NovelHotCommentAdapter(activity!!,bean.user.userId,object : NovelHotCommentAdapter.OnClickPraiseListener{
                override fun onClick(id:Int,position: Int, cancel: Boolean) {
                    if (!AccountService.getInstance().checkAndLogin()) {
                        return
                    }
                    //点赞
                    mPresenter.praiseComment(id,position,cancel)
                }
            })
            hotCommentAdapter!!.setData(bean.hot_comments)
            val manager = object : LinearLayoutManager(activity, VERTICAL, false) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rvHotComment.layoutManager = manager
            rvHotComment.adapter = hotCommentAdapter
            tvToAllComment.visibility = View.VISIBLE
        }else{
            tvToAllComment.visibility = View.GONE
        }
        if (bean.has_fav) {
            ivCollect.setImageResource(R.drawable.read_more_collection_st)
        }else{
            ivCollect.setImageResource(R.drawable.read_more_collection)
        }
        setYouthModel()
    }

    override fun fillRecommendByAuthor(list: MutableList<NovelRecommendBean>, hasMore: Boolean) {
        try {
            if (list != null && list.size > 0) {
                if (hasMore) {
                    layRecommendAuthorReplace.visibility = View.VISIBLE
                }else{
                    layRecommendAuthorReplace.visibility = View.INVISIBLE
                }
                layRecommendByAuthor.visibility = View.VISIBLE
                val adapter = NovelRecommendGridAdapter(activity!!,4)
                adapter.setData(list)
                val manager = object : GridLayoutManager(activity,4){
                    override fun canScrollVertically(): Boolean {
                        return false
                    }
                }
                rvRecommendByAuthor.layoutManager = manager
                rvRecommendByAuthor.adapter = adapter

            }else{
                layRecommendByAuthor.visibility = View.GONE
            }
            setYouthModel()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun fillRecommendByNovel(list: MutableList<NovelRecommendBean>) {
        if (list.size > 0) {
            layRecommendByNovel.visibility = View.VISIBLE
            val adapter = NovelRecommendAdapter(activity!!)
            adapter.setData(list)
            val manager = object : LinearLayoutManager(activity){
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rvRecommendByNovel.layoutManager = manager
            rvRecommendByNovel.adapter = adapter
            setYouthModel()
        }
    }

    override fun praiseComment(position: Int, cancel: Boolean, success: Boolean) {
        if (success && hotCommentAdapter != null && hotCommentAdapter?.dataList?.size!! > position) {
            if (cancel) {
                hotCommentAdapter!!.dataList[position].like_times-=1
                hotCommentAdapter!!.dataList[position].has_liked = 0
            }else{
                hotCommentAdapter!!.dataList[position].has_liked = 1
                hotCommentAdapter!!.dataList[position].like_times+=1
            }
            hotCommentAdapter!!.notifyDataSetChanged()
        }
    }

    override fun collectNovel(isCollect: Boolean, collectTimes: Int) {
        if(isCollect){
            ivCollect.setImageResource(R.drawable.read_more_collection_st)
        }else{
            ivCollect.setImageResource(R.drawable.read_more_collection)
        }
    }




    companion object{

        fun newInstance(novelId: Int):NovelReadEndFragment {
            val fragment = NovelReadEndFragment()
            val bundle = Bundle()
            bundle.putInt(Constant.ID, novelId)
            fragment.arguments = bundle
            return fragment
        }
        fun newInstance(novelId: String):NovelReadEndFragment {
            return newInstance(novelId.toInt())
        }
    }


}